package com.learning.server.net;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class TripleDES {

    private static final String ALGORITHM = "DESede";

    //默认为 DESede/ECB/PKCS5Padding
    private static final String CIPHER_TRANSFORMAT = "DESede/ECB/PKCS5Padding";

    private static final String ENCODING = "utf-8";

    public static byte[] encrypt(String plainText, byte[] key) throws Exception {
        SecretKey deskey = new SecretKeySpec(key, ALGORITHM);
        Cipher c1 = Cipher.getInstance(CIPHER_TRANSFORMAT);
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] result = c1.doFinal(plainText.getBytes(ENCODING));
//        return Base64.encodeBase64(result);
        return result;
    }

    public static String decrypt(String base64, String key) throws Exception {
        SecretKey deskey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher c1 = Cipher.getInstance(CIPHER_TRANSFORMAT);
        c1.init(Cipher.DECRYPT_MODE, deskey);
        byte[] result = c1.doFinal(Base64.decodeBase64(base64));
        return new String(result, ENCODING);
    }
}
